/*
 * Copyright 2011-2013 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

Components.utils.import("resource://oaa-accessibility-extension/cache-inspector-common.js");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");


/**
 * @file sidebar-element-result-summary.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_AE_SIDEBAR.ElementResultView Object             */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_AE_SIDEBAR.ElementResultView === "undefined") {
  OAA_AE_SIDEBAR.ElementResultView = {};
}


/* ---------------------------------------------------------------- */
/*       Rule Category Cache Item Views and View Controllers        */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.init
 *
 * @desc Initializes the view
 */
 
OAA_AE_SIDEBAR.ElementResultView.init = function () {
  
};


/**
 * @function OAA_AE_SIDEBAR.ElementResultView.initStrings
 *
 * @desc Initializes message strings for view
 */
 
OAA_AE_SIDEBAR.ElementResultView.initStrings = function () {

  if (typeof this.MSG_SELECT_ELEMENT !== 'string') {

    var nls_strings  = OAA_AE_SIDEBAR.nls_strings;

    if (!nls_strings) return;

    this.MSG_SELECT_ELEMENT           = nls_strings.getString('selectElement');
    this.MSG_NO_RULE_RESULTS          = nls_strings.getString("noRuleResults");
    this.MSG_FILTERED_ITEM            = nls_strings.getString("filteredItem");
    this.MSG_FILTERED_ITEMS           = nls_strings.getString("filteredItems");
    this.MSG_NO_ELEMENT_SELECTED      = nls_strings.getString("noElementSelected");
    this.MSG_NO_RULE_SELECTED         = nls_strings.getString("noRuleSelected");
    this.MSG_INFORMATION              = nls_strings.getString("information");
    this.MSG_RULE                     = nls_strings.getString("rule");
    this.MSG_MORE_INFORMATION_RULE    = nls_strings.getString('moreInformationRule')
    
  }
  
};

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.hide
 *
 * @desc Hides the element view controls
 */
 
OAA_AE_SIDEBAR.ElementResultView.hide = function () {

  var vbox_element_result = window.document.getElementById('ID_VBOX_ELEMENT_RESULT_VIEW');
  vbox_element_result.hidden = true;
  
};


/**
 * @function OAA_AE_SIDEBAR.ElementResultView.show
 *
 * @desc Shows the element view controls
 */
 
OAA_AE_SIDEBAR.ElementResultView.show = function () {

  var vbox_element_result = window.document.getElementById('ID_VBOX_ELEMENT_RESULT_VIEW');
  vbox_element_result.hidden = false;
  
};


/* ---------------------------------------------------------------- */
/*               Element Result View Functions                      */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.clear
 *
 * @desc Clears the node results from the tree
 */
 
OAA_AE_SIDEBAR.ElementResultView.clear = function () {

  this.initStrings();
  
  this.visible_tree_items = [];          

  var row = { level : 0,
              container : false,
              open : false,
            
              message : this.MSG_SELECT_ELEMENT,
              message_prop : 'message'
            };
  
  this.visible_tree_items.push(row);               
  
  this.setView();

  this.node_results = [];
  this.node_result  = null;
  
  this.rule_result  = null;
    
//  OAA_AE_SIDEBAR.highlightRemove();
  
};

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.update
 *
 * @desc Shows the node results of a cache item
 *
 * @param {CacheItemResult}  cache_item_result  - filtered cache item result object
 */
 
OAA_AE_SIDEBAR.ElementResultView.update = function (cache_item_result) {

  function getFilteredElementCount(count) {
    var str = "";
    
    if (count === 1) str = count + " " + OAA_AE_SIDEBAR.ElementResultView.MSG_FILTERED_ITEM;
    else str = count + " " + OAA_AE_SIDEBAR.ElementResultView.MSG_FILTERED_ITEMS;
         
    return str;
  }

  var SEVERITY = OpenAjax.a11y.SEVERITY;

  var tree  = window.document.getElementById('ID_TREE_ELEMENT_RESULT_VIEW');

  this.initStrings();
  
  this.node_result  = null;

  this.cache_item_result = cache_item_result;

//  OAA_AE_SIDEBAR.logger.debug("Element Result View: "  + cache_item_result.cache_item);

  if (cache_item_result.hasResults()) {
  
    var tree_view = new OpenAjax.a11y.formatters.TreeViewOfCacheItemResult(cache_item_result);

    this.tree_view = tree_view;

    this.showTree(true);
    
    this.visible_tree_items = tree_view.getOpenNodeResults();

    this.node_results = cache_item_result.getNodeResults();
    
    OAA_AE_SIDEBAR.setSummaryValues(cache_item_result.getNodeResultSummary());

    var IOM = OAA_AE_SIDEBAR.INFORMATION_OPTION;
    OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_VIEW);

  } 
  else {    
  
    this.visible_tree_items = [];          
    this.node_results = [];

    var row = { level : 0,
                container : false,
                open : false,
            
                message : OAA_AE_SIDEBAR.ElementResultView.MSG_NO_RULE_RESULTS,
                message_prop : 'message'
              };

    if (cache_item_result.number_of_node_results_filtered) row.message = getFilteredElementCount(cache_item_result.number_of_node_results_filtered);    
    
    this.visible_tree_items.push(row);               

    OAA_AE_SIDEBAR.setSummaryValues();

  }  

  this.setView();

};


/**
 * @function OAA_AE_SIDEBAR.ElementResultView.setView
 *
 * @desc Shows the node results in a custom tree view
 */
 
OAA_AE_SIDEBAR.ElementResultView.setView = function () {

  var SEVERITY = OpenAjax.a11y.SEVERITY;

  var tree  = window.document.getElementById('ID_TREE_ELEMENT_RESULT_VIEW');

//  OAA_AE_SIDEBAR.logger.debug("Update Node Results Tree View: " + this.visible_tree_items.length);

  var visible_tree_items = this.visible_tree_items;
      
  var treeView = {
    visibleData : visible_tree_items,          
        
    selection   : null,
    treeBox     : null,
 
    isSeparator: function(row){ return false; },
    isSorted: function(){ return false; },
    getImageSrc: function(row,col){ return null; },        
    getRowProperties: function(row){ return ""},
    getColumnProperties: function(colid,col){ return ""},
    cycleHeader : function(col, elem) {},
    
    setTree     : function(treeBox) { 
      this.treeBox = treeBox; 
    },
        
    get rowCount() { 
      return this.visibleData.length;
    },
        
    getCellText : function(row,column) {
      var item  = this.visibleData[row];

      switch (column.id) {
       
      case "ID_TREECOL_RULE_SUMMARY":       
        if (typeof item.rule_label === 'string') return item.rule_label;
        if (typeof item.message  === 'string') return item.message;
        break;
       
      case "ID_TREECOL_RULE_WCAG20_LEVEL":
        if (typeof item.level_label === 'string') return item.level_label;
        break;

      case "ID_TREECOL_RULE_REQUIRED":
        if (typeof item.required_label === 'string') return item.required_label;
        break;
              
      case "ID_TREECOL_RULE_RESULT_VALUE":
        if (typeof item.result_label === 'string') return item.result_label;
        break;
              
      default:
        break;
      }  

      return "";
    },
        
    isContainer: function(row) { 

      var item  = this.visibleData[row];
          
      if (typeof item.container === 'boolean') return item.container; 
      
      return false;           
    },
        
    isContainerEmpty: function(row){ 
      return false;           
    },
        
    isContainerOpen: function(row) { 
      return false;           
    },
        
    getParentIndex: function(row) {
                  
      return -1;
    },
    hasNextSibling: function(row, afterIndex) {
      var thisLevel = this.getLevel(row);
      for (var t = afterIndex + 1; t < this.visibleData.length; t++) {
        var nextLevel = this.getLevel(t);
        if (nextLevel == thisLevel) return true;
        if (nextLevel < thisLevel) break;
      }
      return false;     
    },
    toggleOpenState: function(row){   
    },
       
    getLevel: function(row){ 
      return 0; 
    },
        
    getCellProperties: function(row,column) {

      var item  = this.visibleData[row];
      var property_value = "";

      switch (column.id) {
       
      case "ID_TREECOL_RULE_SUMMARY":
        if (typeof item.rule_prop === 'string') property_value = item.rule_prop;
        break;
       
      case "ID_TREECOL_RULE_RESULT_VALUE":       
        if (typeof item.result_prop === 'string') property_value = item.result_prop;
        break;
       
      default:
        break;
      }  
      
      return property_value;
     
    }
 };
      
  tree.view = treeView;


//  OAA_AE_SIDEBAR.highlightCacheItems(this.cache_item_result);
  
};

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.sortRuleList
 *
 * @desc Sorts the list of rules by a sort property
 */
 
OAA_AE_SIDEBAR.ElementResultView.sortCacheItemResults = function (column) {
  
  var tree = window.document.getElementById('ID_TREE_ELEMENT_RESULT_VIEW');
  
  var column_name;
  var order = tree.getAttribute("sortDirection") == "ascending" ? 1 : -1;
  
  //if the column is passed and it's already sorted by that column, reverse sort
  if (column) {
    column_name = column.id;

    if (tree.getAttribute("sortResource") == column_name) {
      order *= -1;
    }
  } else {
    column_name = tree.getAttribute("sortResource");
  }

  //setting these will make the sort option persist
  tree.setAttribute("sortDirection", order == 1 ? "ascending" : "descending");
  tree.setAttribute("sortResource", column_name);
  
  //set the appropriate attributes to show to indicator
  var cols = tree.getElementsByTagName("treecol");

  for (var i = 0; i < cols.length; i++) {
    cols[i].removeAttribute("sortDirection");
  }

  document.getElementById(column_name).setAttribute("sortDirection", order == 1 ? "ascending" : "descending");

  var tree_view = OAA_AE_SIDEBAR.ElementResultView.tree_view;

  var frc = OAA_AE_SIDEBAR.RuleCategoryView.filtered_rule_category;

  switch (column.id) {
       
  case "ID_TREECOL_RULE_SUMMARY":
    OAA_AE_SIDEBAR.ElementResultView.visible_tree_items = tree_view.sortListOfNodeResults('rule_label', order);
    break;

  case "ID_TREECOL_RULE_WCAG20_LEVEL":
    OAA_AE_SIDEBAR.ElementResultView.visible_tree_items = tree_view.sortListOfNodeResults('level_const', order);
    break;

  case "ID_TREECOL_RULE_REQUIRED":
    OAA_AE_SIDEBAR.ElementResultView.visible_tree_items = tree_view.sortListOfNodeResults('required', order);
    break;

  case "ID_TREECOL_RULE_RESULT_VALUE":       
    OAA_AE_SIDEBAR.ElementResultView.visible_tree_items = tree_view.sortListOfNodeResults('result_value', order);
    break;
              
  default:
    break;
  }  

  OAA_AE_SIDEBAR.ElementResultView.setView();

};


/**
 * @function OAA_AE_SIDEBAR.ElementResultView.setTreeControls
 *
 * @desc Disables or enables tree collapse and expand buttons
 *
 * @param {Boolean}   flag   - If true to enable and false to disable
 */
 
OAA_AE_SIDEBAR.ElementResultView.setTreeControls = function(flag) {

  var button_expand = window.document.getElementById('ID_BUTTON_ELEMENT_RESULT_EXPAND_TREE');
  if (flag) button_expand.setAttribute('disabled', 'false');
  else button_expand.setAttribute('disabled', 'true');

  var button_collapse = window.document.getElementById('ID_BUTTON_ELEMENT_RESULT_COLLAPSE_TREE');
  if (flag) button_collapse.setAttribute('disabled', 'false');
  else button_collapse.setAttribute('disabled', 'true');

};

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.showTree
 *
 * @desc Expands or contracts showing the properties of a node result in a tree view 
 *
 * @param {Boolean}   flag   - If true expand tree to show all properties, if false collapse tree to hide properties
 */
 
OAA_AE_SIDEBAR.ElementResultView.showTree = function(flag) {

  var tree_view = OAA_AE_SIDEBAR.ElementResultView.tree_view;

//  OAA_AE_SIDEBAR.logger.debug("FRR: " + cir + "  IS TREE: " + (cir ? cir.is_tree : null));

  if (tree_view) {
  
    tree_view.setOpenState(flag);
   
    OAA_AE_SIDEBAR.ElementResultView.visible_tree_items = tree_view.getOpenNodeResults();
  
    OAA_AE_SIDEBAR.ElementResultView.setView();    
  }
};



/**
 * @function OAA_AE_SIDEBAR.ElementResultView.nodeResultListOnSelect
 *
 * @desc Updates cache item information button when a cache item is selected
 */
 
OAA_AE_SIDEBAR.ElementResultView.onSelect = function () {

  var IOM = OAA_AE_SIDEBAR.INFORMATION_OPTION;
  var tree  = window.document.getElementById('ID_TREE_ELEMENT_RESULT_VIEW');

  if (tree) {
  
    var index = tree.currentIndex;
    
    if (index < 0) return;
 
    var item = OAA_AE_SIDEBAR.ElementResultView.visible_tree_items[index];

    if (!item) {
      OAA_AE_SIDEBAR.ElementResultView.node_result = null;
      OAA_AE_SIDEBAR.showCurrentRulesetInformation();
      OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_VIEW);
    }
    else {
      var node_result  = item.node_result;
      OAA_AE_SIDEBAR.ElementResultView.node_result = node_result;
      OAA_AE_SIDEBAR.showNodeResultInformation(node_result);
      OAA_AE_SIDEBAR.setInformationMenuOption(IOM.CURRENT_SELECTION);
    }

//  OAA_AE_SIDEBAR.logger.debug(" Node Result: " + node_result);  

    
  }
};

/**
 * @function OAA_AE_SIDEBAR.ElementResultView.showNodeResultInformation
 *
 * @desc Show information about the currently selected element 
 */
 
OAA_AE_SIDEBAR.ElementResultView.showNodeResultInformation = function () {

  var node_result = OAA_AE_SIDEBAR.ElementResultView.node_result;

  if (node_result) {
    OAA_AE_SIDEBAR.showRulePropertiesDialog(node_result);
  }

};

